package com.zyl.Ecs.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.zyl.Ecs.common.constant.ConfigConstant;
import com.zyl.Ecs.common.exception.EcsException;
import com.zyl.Ecs.common.response.Result;
import com.zyl.Ecs.common.utils.CUtil;
import com.zyl.Ecs.common.utils.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.gateway.filter
 * @ClassName: JwtTokenFilter
 * @Description TODO
 * @Author 翟玉龙
 * @Date 2024/12/5-8:47
 */
@Data
@Component
@RequiredArgsConstructor
public class JwtTokenFilter implements GlobalFilter, Ordered {

    @Value("${zyl.config.white-list}")
    private List<String> whiteList;

    /**
     * 请求到来时自动调用的方法
     *
     * @param exchange 请求和响应对象
     * @param chain    过滤链
     * @return {@link Mono }<{@link Void }>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            return filter0(exchange, chain);
        } catch (EcsException e) {
            CUtil.logInfo(e.getMessage());
            return responseError(exchange, e.getMessage());
        }
    }

    /**
     * 自定义过滤方法，方便统一处理异常
     *
     * @param exchange 请求和响应对象
     * @param chain 过滤链
     * @return {@link Mono }<{@link Void }>
     * @throws EcsException ecs异常
     */
    private Mono<Void> filter0(ServerWebExchange exchange, GatewayFilterChain chain) throws EcsException {

        /* 观察Filter是否被调用 */
        CUtil.logInfo("filter....");

        /* 获取请求对象 */
        ServerHttpRequest request = exchange.getRequest();
        /* 获取请求方法 */
        HttpMethod method = request.getMethod();
        /* 获取请求路径 */
        String path = request.getURI().getPath();

        /* 如果请求URL在白名单，则直接放行，否则校验Token合法性 */
        if (inWhiteList(path)) {
            CUtil.logInfo("[gateway]白名单URL，直接放行：" + path);
            return chain.filter(exchange);
        }

        /* 获取请求头中的Token */
        String token = request.getHeaders().getFirst(
                ConfigConstant.AUTH_HEADER_KEY);

        CUtil.logInfo("[token]" + token);
        /* 校验Token */
        JwtUtil.checkSign(token);

        /* 通过认证后放行 */
        return chain.filter(exchange);
    }

    /**
     * 判断请求路径是否在白名单中
     *
     * @param path 请求路径
     * @return boolean
     */
    private boolean inWhiteList(String path) {
        return whiteList.contains(path);
    }

    /**
     * 定义优先级
     *
     * @return 返回值越小则优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 响应错误
     *
     * @param exchange 请求和响应对象
     * @param message 消息
     * @return {@link Mono }<{@link Void }>
     */
    private Mono<Void> responseError(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        Result<?> result = Result.error(message);
        String str = JSONObject.toJSONString(result);
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        response.setStatusCode(HttpStatus.OK);
        /* 注意设置响应头部编码，否则在浏览器中会中文乱码 */
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
